{% extends "base.html" %}

{% block title %}用户注册 - 个人工具网站集{% endblock %}

{% block content %}
<div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
        <div class="bg-white rounded-xl shadow-lg p-8">
            <!-- 标题 -->
            <div class="text-center mb-8">
                <div class="mx-auto h-12 w-12 bg-blue-100 rounded-full flex items-center justify-center mb-4">
                    <i class="fas fa-user-plus text-blue-600 text-xl"></i>
                </div>
                <h2 class="text-3xl font-bold text-gray-900 mb-2">创建账户</h2>
                <p class="text-gray-600">加入我们，开始使用强大的工具集</p>
            </div>
            
            <!-- 注册表单 -->
            <form method="POST" id="registerForm" class="space-y-6">
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-user mr-2"></i>用户名
                    </label>
                    <input type="text" id="username" name="username" required 
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                           placeholder="请输入用户名">
                    <div class="text-sm text-gray-500 mt-1">用户名长度为3-20个字符，只能包含字母、数字和下划线</div>
                </div>
                
                <div>
                    <label for="email" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-envelope mr-2"></i>邮箱地址
                    </label>
                    <input type="email" id="email" name="email" required 
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                           placeholder="请输入邮箱地址">
                    <div class="text-sm text-gray-500 mt-1">我们将向此邮箱发送验证邮件</div>
                </div>
                
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-lock mr-2"></i>密码
                    </label>
                    <div class="relative">
                        <input type="password" id="password" name="password" required 
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors pr-12"
                               placeholder="请输入密码">
                        <button type="button" onclick="togglePassword('password')" 
                                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600">
                            <i class="fas fa-eye" id="password-eye"></i>
                        </button>
                    </div>
                    <div class="text-sm text-gray-500 mt-1">密码长度至少8位，包含字母和数字</div>
                </div>
                
                <div>
                    <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-lock mr-2"></i>确认密码
                    </label>
                    <div class="relative">
                        <input type="password" id="confirm_password" name="confirm_password" required 
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors pr-12"
                               placeholder="请再次输入密码">
                        <button type="button" onclick="togglePassword('confirm_password')" 
                                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600">
                            <i class="fas fa-eye" id="confirm_password-eye"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 密码强度指示器 -->
                <div id="passwordStrength" class="hidden">
                    <div class="text-sm font-medium text-gray-700 mb-2">密码强度</div>
                    <div class="flex space-x-1">
                        <div class="h-2 flex-1 bg-gray-200 rounded" id="strength1"></div>
                        <div class="h-2 flex-1 bg-gray-200 rounded" id="strength2"></div>
                        <div class="h-2 flex-1 bg-gray-200 rounded" id="strength3"></div>
                        <div class="h-2 flex-1 bg-gray-200 rounded" id="strength4"></div>
                    </div>
                    <div class="text-sm mt-1" id="strengthText">请输入密码</div>
                </div>
                
                <!-- 服务条款 -->
                <div class="flex items-start">
                    <input type="checkbox" id="terms" name="terms" required 
                           class="mt-1 h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                    <label for="terms" class="ml-3 text-sm text-gray-600">
                        我已阅读并同意 
                        <a href="#" class="text-blue-600 hover:text-blue-500 underline">服务条款</a> 
                        和 
                        <a href="#" class="text-blue-600 hover:text-blue-500 underline">隐私政策</a>
                    </label>
                </div>
                
                <!-- 提交按钮 -->
                <button type="submit" id="submitBtn" 
                        class="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors font-medium">
                    <span id="submitText">
                        <i class="fas fa-user-plus mr-2"></i>创建账户
                    </span>
                    <span id="submitLoading" class="hidden">
                        <i class="fas fa-spinner fa-spin mr-2"></i>注册中...
                    </span>
                </button>
            </form>
            
            <!-- 重新发送验证邮件区域 -->
            {% if show_resend and unverified_email %}
            <div class="mt-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                <div class="flex items-start">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-600"></i>
                    </div>
                    <div class="ml-3 flex-1">
                        <h3 class="text-sm font-medium text-yellow-800">邮箱未验证</h3>
                        <p class="text-sm text-yellow-700 mt-1">
                            邮箱 <strong>{{ unverified_email }}</strong> 已注册但未验证
                        </p>
                        <div class="mt-3">
                            <form method="POST" action="{{ url_for('resend_verification') }}" class="inline">
                                <input type="hidden" name="email" value="{{ unverified_email }}">
                                <button type="submit" id="resendBtn" 
                                        class="bg-yellow-600 text-white px-4 py-2 rounded-lg hover:bg-yellow-700 focus:ring-2 focus:ring-yellow-500 focus:ring-offset-2 transition-colors text-sm font-medium">
                                    <span id="resendText">
                                        <i class="fas fa-paper-plane mr-2"></i>重新发送验证邮件
                                    </span>
                                    <span id="resendLoading" class="hidden">
                                        <i class="fas fa-spinner fa-spin mr-2"></i>发送中...
                                    </span>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            {% endif %}
            
            <!-- 登录链接 -->
            <div class="mt-6 text-center">
                <p class="text-sm text-gray-600">
                    已有账户？
                    <a href="{{ url_for('login') }}" class="text-blue-600 hover:text-blue-500 font-medium underline">
                        立即登录
                    </a>
                </p>
            </div>
            
            <!-- 社交登录 -->
            <div class="mt-6">
                <div class="relative">
                    <div class="absolute inset-0 flex items-center">
                        <div class="w-full border-t border-gray-300"></div>
                    </div>
                    <div class="relative flex justify-center text-sm">
                        <span class="px-2 bg-white text-gray-500">或使用以下方式注册</span>
                    </div>
                </div>
                
                <div class="mt-6 grid grid-cols-2 gap-3">
                    <button class="w-full inline-flex justify-center py-2 px-4 border border-gray-300 rounded-lg shadow-sm bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 transition-colors">
                        <i class="fab fa-github text-lg"></i>
                        <span class="ml-2">GitHub</span>
                    </button>
                    <button class="w-full inline-flex justify-center py-2 px-4 border border-gray-300 rounded-lg shadow-sm bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 transition-colors">
                        <i class="fab fa-google text-lg"></i>
                        <span class="ml-2">Google</span>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 注册优势 -->
        <div class="bg-white rounded-xl shadow-lg p-6 mt-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4 text-center">
                <i class="fas fa-star text-yellow-500 mr-2"></i>注册后您将获得
            </h3>
            <div class="space-y-3">
                <div class="flex items-center">
                    <div class="flex-shrink-0 w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-upload text-green-600 text-sm"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">上传自定义工具</p>
                        <p class="text-sm text-gray-500">上传您的HTML工具，与他人分享</p>
                    </div>
                </div>
                
                <div class="flex items-center">
                    <div class="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-bookmark text-blue-600 text-sm"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">收藏喜爱工具</p>
                        <p class="text-sm text-gray-500">快速访问您常用的工具</p>
                    </div>
                </div>
                
                <div class="flex items-center">
                    <div class="flex-shrink-0 w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-chart-line text-purple-600 text-sm"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">使用统计分析</p>
                        <p class="text-sm text-gray-500">查看工具使用情况和数据</p>
                    </div>
                </div>
                
                <div class="flex items-center">
                    <div class="flex-shrink-0 w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-bell text-red-600 text-sm"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">新工具通知</p>
                        <p class="text-sm text-gray-500">第一时间了解新增工具</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 表单验证和交互
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('registerForm');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirm_password');
    const usernameInput = document.getElementById('username');
    const emailInput = document.getElementById('email');
    
    // 密码强度检测
    passwordInput.addEventListener('input', function() {
        checkPasswordStrength(this.value);
        validatePasswordMatch();
    });
    
    // 确认密码验证
    confirmPasswordInput.addEventListener('input', validatePasswordMatch);
    
    // 用户名验证
    usernameInput.addEventListener('blur', validateUsername);
    
    // 邮箱验证
    emailInput.addEventListener('blur', validateEmail);
    
    // 表单提交
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (validateForm()) {
            submitForm();
        }
    });
    
    // 重新发送验证邮件按钮事件
    const resendBtn = document.getElementById('resendBtn');
    if (resendBtn) {
        resendBtn.addEventListener('click', function(e) {
            e.preventDefault();
            resendVerificationEmail();
        });
    }
});

function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const eye = document.getElementById(inputId + '-eye');
    
    if (input.type === 'password') {
        input.type = 'text';
        eye.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        eye.className = 'fas fa-eye';
    }
}

function checkPasswordStrength(password) {
    const strengthDiv = document.getElementById('passwordStrength');
    const strengthText = document.getElementById('strengthText');
    const strengthBars = [1, 2, 3, 4].map(i => document.getElementById('strength' + i));
    
    if (password.length === 0) {
        strengthDiv.classList.add('hidden');
        return;
    }
    
    strengthDiv.classList.remove('hidden');
    
    let strength = 0;
    let feedback = [];
    
    // 长度检查
    if (password.length >= 8) {
        strength++;
    } else {
        feedback.push('至少8个字符');
    }
    
    // 包含小写字母
    if (/[a-z]/.test(password)) {
        strength++;
    } else {
        feedback.push('包含小写字母');
    }
    
    // 包含大写字母
    if (/[A-Z]/.test(password)) {
        strength++;
    } else {
        feedback.push('包含大写字母');
    }
    
    // 包含数字
    if (/\d/.test(password)) {
        strength++;
    } else {
        feedback.push('包含数字');
    }
    
    // 包含特殊字符
    if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
        strength++;
    }
    
    // 更新强度条
    strengthBars.forEach((bar, index) => {
        if (index < strength) {
            if (strength <= 2) {
                bar.className = 'h-2 flex-1 bg-red-500 rounded';
            } else if (strength <= 3) {
                bar.className = 'h-2 flex-1 bg-yellow-500 rounded';
            } else {
                bar.className = 'h-2 flex-1 bg-green-500 rounded';
            }
        } else {
            bar.className = 'h-2 flex-1 bg-gray-200 rounded';
        }
    });
    
    // 更新文本
    if (strength <= 2) {
        strengthText.textContent = '弱：' + feedback.join('、');
        strengthText.className = 'text-sm mt-1 text-red-600';
    } else if (strength <= 3) {
        strengthText.textContent = '中等：建议' + feedback.join('、');
        strengthText.className = 'text-sm mt-1 text-yellow-600';
    } else {
        strengthText.textContent = '强：密码安全性良好';
        strengthText.className = 'text-sm mt-1 text-green-600';
    }
}

function validatePasswordMatch() {
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm_password').value;
    const confirmInput = document.getElementById('confirm_password');
    
    if (confirmPassword && password !== confirmPassword) {
        confirmInput.classList.add('border-red-500');
        confirmInput.classList.remove('border-gray-300');
        showFieldError(confirmInput, '两次输入的密码不一致');
        return false;
    } else if (confirmPassword) {
        confirmInput.classList.remove('border-red-500');
        confirmInput.classList.add('border-green-500');
        hideFieldError(confirmInput);
        return true;
    }
    return true;
}

function validateUsername() {
    const username = document.getElementById('username').value;
    const usernameInput = document.getElementById('username');
    
    if (username.length < 3 || username.length > 20) {
        usernameInput.classList.add('border-red-500');
        showFieldError(usernameInput, '用户名长度应为3-20个字符');
        return false;
    }
    
    if (!/^[a-zA-Z0-9_]+$/.test(username)) {
        usernameInput.classList.add('border-red-500');
        showFieldError(usernameInput, '用户名只能包含字母、数字和下划线');
        return false;
    }
    
    usernameInput.classList.remove('border-red-500');
    usernameInput.classList.add('border-green-500');
    hideFieldError(usernameInput);
    return true;
}

function validateEmail() {
    const email = document.getElementById('email').value;
    const emailInput = document.getElementById('email');
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    
    if (!emailRegex.test(email)) {
        emailInput.classList.add('border-red-500');
        showFieldError(emailInput, '请输入有效的邮箱地址');
        return false;
    }
    
    emailInput.classList.remove('border-red-500');
    emailInput.classList.add('border-green-500');
    hideFieldError(emailInput);
    return true;
}

function showFieldError(field, message) {
    // 移除现有错误信息
    const existingError = field.parentNode.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
    
    // 添加新错误信息
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error text-sm text-red-600 mt-1';
    errorDiv.textContent = message;
    field.parentNode.appendChild(errorDiv);
}

function hideFieldError(field) {
    const errorDiv = field.parentNode.querySelector('.field-error');
    if (errorDiv) {
        errorDiv.remove();
    }
}

function validateForm() {
    const username = validateUsername();
    const email = validateEmail();
    const passwordMatch = validatePasswordMatch();
    const terms = document.getElementById('terms').checked;
    
    if (!terms) {
        alert('请同意服务条款和隐私政策');
        return false;
    }
    
    return username && email && passwordMatch;
}

function submitForm() {
    const submitBtn = document.getElementById('submitBtn');
    const submitText = document.getElementById('submitText');
    const submitLoading = document.getElementById('submitLoading');
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitText.classList.add('hidden');
    submitLoading.classList.remove('hidden');
    
    // 获取表单数据
    const formData = new FormData(document.getElementById('registerForm'));
    
    // 发送请求
    fetch('{{ url_for("register") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: formData.get('username'),
            email: formData.get('email'),
            password: formData.get('password')
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 注册成功
            showSuccessMessage(data.message || '注册成功！请检查您的邮箱并点击验证链接。');
            setTimeout(() => {
                if (data.redirect_url) {
                    window.location.href = data.redirect_url;
                } else {
                    window.location.href = '{{ url_for("email_verification") }}';
                }
            }, 2000);
        } else {
            // 注册失败
            showErrorMessage(data.message || '注册失败，请重试');
            
            // 如果是邮箱已存在但未验证的情况，显示重新发送按钮
            if (data.show_resend && data.unverified_email) {
                showResendSection(data.unverified_email);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showErrorMessage('网络错误，请重试');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitText.classList.remove('hidden');
        submitLoading.classList.add('hidden');
    });
}

function showSuccessMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-check-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

function showErrorMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-exclamation-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

function showResendSection(email) {
    // 更新邮箱输入框的值
    const emailInput = document.querySelector('input[name="email"]');
    if (emailInput) {
        emailInput.value = email;
    }
    
    // 显示重新发送验证邮件的区域
    const resendSection = document.getElementById('resendSection');
    if (resendSection) {
        resendSection.classList.remove('hidden');
    } else {
        // 如果没有找到现有的重新发送区域，动态创建一个
        const form = document.getElementById('registerForm');
        const resendHtml = `
            <div id="resendSection" class="mt-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                <div class="flex items-center mb-3">
                    <i class="fas fa-exclamation-triangle text-yellow-600 mr-2"></i>
                    <span class="text-yellow-800 font-medium">邮箱未验证</span>
                </div>
                <p class="text-yellow-700 mb-4">该邮箱已注册但未验证，请检查邮箱或重新发送验证邮件。</p>
                <form id="resendForm" class="flex gap-3">
                    <input type="hidden" name="email" value="${email}">
                    <button type="submit" id="resendBtn" class="flex-1 bg-yellow-600 text-white py-2 px-4 rounded-lg hover:bg-yellow-700 transition duration-200 flex items-center justify-center">
                        <span id="resendText">重新发送验证邮件</span>
                        <div id="resendLoading" class="hidden flex items-center">
                            <svg class="animate-spin h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            发送中...
                        </div>
                    </button>
                </form>
            </div>
        `;
        form.insertAdjacentHTML('afterend', resendHtml);
        
        // 为新创建的按钮添加事件监听器
        const newResendBtn = document.getElementById('resendBtn');
        if (newResendBtn) {
            newResendBtn.addEventListener('click', function(e) {
                e.preventDefault();
                resendVerificationEmail();
            });
        }
    }
}

function resendVerificationEmail() {
    const resendBtn = document.getElementById('resendBtn');
    const resendText = document.getElementById('resendText');
    const resendLoading = document.getElementById('resendLoading');
    const emailInput = document.querySelector('#resendForm input[name="email"]') || document.querySelector('input[name="email"]');
    
    if (!emailInput || !emailInput.value) {
        showErrorMessage('邮箱地址不能为空');
        return;
    }
    
    // 禁用按钮并显示加载状态
    resendBtn.disabled = true;
    resendText.classList.add('hidden');
    resendLoading.classList.remove('hidden');
    
    // 创建表单数据
    const formData = new FormData();
    formData.append('email', emailInput.value);
    
    // 发送请求
    fetch('{{ url_for("resend_verification") }}', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (response.redirected) {
            // 如果服务器返回重定向，直接跳转
            window.location.href = response.url;
            return;
        }
        return response.json();
    })
    .then(data => {
        if (data && data.success) {
            showSuccessMessage(data.message || '验证邮件已重新发送');
            // 3秒后跳转到邮箱验证页面
            setTimeout(() => {
                window.location.href = '{{ url_for("email_verification") }}';
            }, 3000);
        } else if (data && data.message) {
            showErrorMessage(data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showErrorMessage('网络错误，请重试');
    })
    .finally(() => {
        // 恢复按钮状态
        resendBtn.disabled = false;
        resendText.classList.remove('hidden');
        resendLoading.classList.add('hidden');
    });
}
</script>
{% endblock %}